package cn.mall.order.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.*;
import java.net.Authenticator;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class NewGetDataUtils {

    public static void main(String[] args) {


//        String filePath = "D:\\weibo_mall\\src\\main\\resources\\links.txt"; // 替换为你的文件路径
//        List<String> links = new ArrayList<>();
//
//        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
//            String line;
//            while ((line = br.readLine()) != null) {
//// 去除可能存在的多余空白字符
//                line = line.trim();
//                if (!line.isEmpty()) {
//// links.add(line);
//                    HashMap<String, Integer> map = wayDataBase(line);
//                    System.out.println("===================================================");
//                    System.out.println("url:"+line);
//                    for (Map.Entry<String, Integer> entry : map.entrySet()) {
//                        System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
//                    }
//                }
//            }
//        } catch (IOException e) {
//            System.err.println("Error reading file: " + e.getMessage());
//        }
        String s ="https://m.weibo.cn/status/OfzWdbiEX";
        HashMap<String, Integer> map = wayDataBase(s);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }

    }

    public static HashMap<String,Integer> wayDataBase(String str){
        String s = dealStr(str);
        HashMap<String, Integer> map = new HashMap<>();
        try {
            String s1 = newData(s);
            JSONObject jsonObject = new JSONObject(s1);
            String reposts_count = jsonObject.getString("reposts_count");
            int i = Integer.parseInt(reposts_count);
            map.put("reposts_count",i);

            String comments_count = jsonObject.getString("comments_count");
            int i1 = Integer.parseInt(comments_count);
            map.put("comments_count",i1);

            String attitudes_count = jsonObject.getString("attitudes_count");
            int i2 = Integer.parseInt(attitudes_count);
            map.put("attitudes_count",i2);
//            if(jsonObject.getJSONObject("page_info")!=null){
//                JSONObject page_info = jsonObject.getJSONObject("page_info");
//                JSONObject media_info = page_info.getJSONObject("media_info");
//                String online_users_number = media_info.getString("online_users_number");
//                int i3 = Integer.parseInt(online_users_number);
//                map.put("online_users_number",i3);
//            }

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return map;
    }
    public static HashMap<String,Integer> wayDataVideo(String str){
        String s = dealStr(str);
        HashMap<String, Integer> map = new HashMap<>();
        try {
            String s1 = newData(s);
            System.out.println(s1);
            JSONObject jsonObject = new JSONObject(s1);
            if(jsonObject.getJSONObject("page_info")!=null){
                JSONObject page_info = jsonObject.getJSONObject("page_info");
                JSONObject media_info = page_info.getJSONObject("media_info");
                String online_users_number = media_info.getString("online_users_number");
                int i3 = Integer.parseInt(online_users_number);
                map.put("online_users_number",i3);
            }

        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return map;
    }


    public static String getWeiboData(String url) throws IOException, JSONException {
        List<JSONObject> data = userIp();
        Random random = new Random();
        int randomIndex = random.nextInt(data.size());
//        System.out.println("---------");
//        System.out.println(data.get(randomIndex).toString());
        String proxyHost = data.get(randomIndex).get("ip").toString();
        String port = data.get(randomIndex).get("port").toString();
        Integer proxyPort = Integer.parseInt(port);
        String username = data.get(randomIndex).get("username").toString();
        String password = data.get(randomIndex).get("password").toString();
        Authenticator proxyAuthenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        };
        Authenticator.setDefault(proxyAuthenticator);
//        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
//        OkHttpClient client = new OkHttpClient.Builder()
//                .connectTimeout(5, TimeUnit.SECONDS)
//                .writeTimeout(5, TimeUnit.SECONDS)
//                .readTimeout(5, TimeUnit.SECONDS)
//                .callTimeout(10, TimeUnit.SECONDS)
//                .proxy(proxy)
//                .build();
//        Request request = new Request.Builder().url(url).build();
//        Response response = client.newCall(request).execute();
//
//        return response.body().string();

        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 延长超时时间
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .proxy(proxy)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }


//        HttpClient httpClient = HttpClientBuilder.create().build();
//        HttpGet httpGet = new HttpGet(url);
//        HttpResponse response = httpClient.execute(httpGet);
//        return EntityUtils.toString(response.getEntity());
    }

    public static String newData(String s) throws IOException, JSONException {

        URL url1 = new URL("https://passport.weibo.com/visitor/genvisitor2");
        String token = getSub(url1);
        String subValue = getSubValue(token);
        String requestUrl = "https://weibo.com/ajax/statuses/show?id=" + s + "&locale=zh-CN";


        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置请求方法为GET
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br, zstd");
        connection.setRequestProperty("cookie","SUB="+subValue);

        // 连接并获取响应码
        connection.connect();
        int responseCode = connection.getResponseCode();
//        System.out.println("Response Code : " + responseCode);
        String charset = connection.getContentEncoding();
//        System.out.println(charset);
        // 读取响应内容
//        BufferedReader in = null;
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            // 不需要显式调用 in.close();，因为 try-with-resources 会自动处理
        } catch (IOException e) {
            e.printStackTrace();
            // 在这里处理异常后的逻辑，比如返回错误响应、记录日志等
        }
// 在这里继续执行后续逻辑
        // 打印响应内容
//        System.out.println(response.toString());
        // 关闭连接
        connection.disconnect();
        return response.toString();
    }

    public static String getSub(URL url) throws IOException
    {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setDoOutput(true);

            Map<String, String> params = new HashMap<>();
            params.put("cb", "visitor_gray_callback");
            params.put("tid", "");
            params.put("from", "weibo");

            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(encode(param.getKey())).append('=').append(encode(param.getValue()));
            }

            byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
            connection.setFixedLengthStreamingMode(postDataBytes.length);

            try (java.io.OutputStream os = connection.getOutputStream()) {
                os.write(postDataBytes);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode >= 200 && responseCode < 300) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {

                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return response.toString();
                }
            } else {
                throw new IOException("Unexpected response code: " + responseCode);
            }
        } finally {
            connection.disconnect();
        }

    }
    public static String getSubValue(String s){

        // 使用正则表达式提取JSON字符串部分
        Pattern pattern = Pattern.compile("visitor_gray_callback\\((.*)\\);");
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            String jsonString = matcher.group(1);

            // 使用Jackson库解析JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                JsonNode dataNode = rootNode.get("data");
                String subValue = dataNode.get("sub").asText();

                // 输出sub字段的值
//                System.out.println("sub字段的值: " + subValue);
                return subValue;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            System.out.println("没有找到JSON部分");
            return null;
        }
        return null;
    }
    private static String encode(String s) {
        try {
            return java.net.URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError("编码解析有误", e);
        }
    }

    public static List<JSONObject> userIp(){
        List<JSONObject> dataList = new ArrayList<>();
        String filePath = "proxy.txt"; // 文本文件路径 D:\weibo_mall\src\main\resources\proxy.txt
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设每行数据都符合 "IP----端口----username----password----时间" 的格式
                String[] parts = line.split("----");
                if (parts.length == 5) {
                    String ip = parts[0].trim();
                    String port = parts[1].trim();
                    String username = parts[2].trim();
                    String password = parts[3].trim();
                    // 忽略时间部分
                    // 创建JSONObject并添加到列表中
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("ip", ip);
                    jsonObject.put("port", port);
                    jsonObject.put("username", username);
                    jsonObject.put("password", password); // 注意：在实际应用中，避免存储或传输明文密码
                    dataList.add(jsonObject);
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return dataList;
    }

    public static String dealStr(String str){
        String[] parts = str.split("\\?");
//        System.out.println(parts[0]);
        String part = parts[0];
        String[] split = part.split("/");
        if(split.length==0){
            return null;
        }
        return split[4];
    }

}

